'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
  async sendsms() {
    const { ctx, app } = this;
    const { phone } = ctx.request.body;
    if (!phone) {
      ctx.body = { success: false, msg: '请传入接收短信的手机号' };
    }
    try {
      const Code = await app.redis.get(phone);
      console.info('redis', Code);
      const Tcode = Code ? Code : Math.random().toString().slice(-6);
      console.info('随机数', Tcode);
      const res = await ctx.sms.sendSMS({
        PhoneNumbers: phone,
        SignName: '影记摄影app',
        TemplateCode: 'SMS_204456018',
        TemplateParam: `{"code": "${Tcode}"}`,
      });
      ctx.body = { success: true, msg: '发送成功', data: res };
      const awaittime = 60 * 5;
      await app.redis.set(phone, Tcode, 'ex', awaittime);
    } catch (e) {
      console.info(e);
      ctx.body = { success: false, msg: '发送失败' };
    }
  }
  async isregister() {
    const { ctx, app } = this;
    const { Code, phone } = ctx.request.body;
    try {
      const Tcode = await app.redis.get(phone);
      if (Tcode === null) {
        ctx.body = { success: false, msg: '验证码超时' };
      } else if (Code === Tcode) {
        ctx.body = { success: true, msg: '验证码匹配' };
        await app.redis.del(phone);
      } else {
        ctx.body = { success: false, msg: '验证码错误' };
      }
    } catch (e) {
      ctx.body = { success: false, msg: e };
    }
  }

}
module.exports = HomeController;
